package cn.bytepath.product.controller;

import cn.bytepath.product.domain.Product;
import cn.bytepath.product.query.ProductQuery;
import cn.bytepath.product.service.IProductService;
import cn.bytepath.util.PageInfo;
import cn.bytepath.util.PageResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 产品的控制层
 * @author Jack.C
 * @createDate 2022-01-24
 * @version 1.0
 */
@Api(tags = "产品接口",description = "产品接口详细描述")
@RestController
@RequestMapping("/product")
public class ProductController {

    /**
     * 注入产品业务层对象
     */
    @Autowired
    private IProductService productService;

    @ApiOperation("查询所有产品对象")
    @GetMapping
    public List<Product> findAll() {
        return productService.findAll();
    }

    @ApiOperation("高级查询并分页")
    @PostMapping
    public PageInfo<Product> pageQuery(@RequestBody ProductQuery query) {
        return productService.findPageInfoByQuery(query);
    }

    @ApiOperation("根据id删除产品对象")
    @DeleteMapping("/{id}")
    public PageResult delete(@PathVariable("id") Long id) {

        try {
            productService.delete(id);
            return PageResult.SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return PageResult.FAIL.setMsg(e.getMessage());
        }
    }

    @ApiOperation("根据id批量删除产品对象")
    @PatchMapping
    public PageResult deleteBatch(@RequestBody Long[] ids) {

        try {
            productService.deleteBatch(ids);
            return PageResult.SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return PageResult.FAIL.setMsg(e.getMessage());
        }
    }

    @ApiOperation(value = "产品添加或修改",notes = "如果有id就是修改否则就是添加")
    @PutMapping
    public PageResult saveOrUpdate(@RequestBody Product Product) {
        System.out.println(Product);
        try {
            productService.saveOrUpdate(Product);
            return PageResult.SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return PageResult.FAIL.setMsg(e.getMessage());
        }
    }
}
